package com.practice.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.practice.common.context.BaseContext;
import com.practice.common.result.PageResult;
import com.practice.common.result.Result;
import com.practice.mapper.user.ArticleMapper;
import com.practice.mapper.user.UUserMapper;
import com.practice.mapper.user.UserDataMapper;
import com.practice.pojo.user.dto.*;
import com.practice.pojo.user.entity.Article;
import com.practice.pojo.user.entity.User;
import com.practice.pojo.user.entity.UserData;
import com.practice.pojo.user.vo.UserInfoVO;
import com.practice.service.user.UUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UUserServiceImpl implements UUserService {

    @Autowired
    private UUserMapper uUserMapper;

    @Autowired
    private UserDataMapper userDataMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Result getUserInfo() {
        //查询用户信息
        //先得到id 
        Long id = BaseContext.getCurrentId();
        User user = uUserMapper.selectById(id);
        //查询文章数量
        Long articleNum = articleMapper.selectCount(new LambdaQueryWrapper<Article>().eq(Article::getUserId, id));

        //查询点赞数量
        //查询收藏数量
        Long collectNum = 0L;
        Long zanNum = 0L;
        List<UserData> userDataList = userDataMapper.selectList(new LambdaQueryWrapper<UserData>().
                eq(UserData::getUserId, id));
        for (UserData userData : userDataList) {
            if (userData.getType() == 1) {
                collectNum++;
            }
            if (userData.getType() == 2) {
                zanNum++;
            }
        }
        return Result.success(new UserInfoVO(
                articleNum,
                collectNum,
                zanNum,
                user
        ));
    }

    @Override
    public Result myArticle(PageQueryDTO dto) {
        //1 创建IPage分页对象,设置分页参数
        IPage<Article> page = new Page<>(dto.getPage(), dto.getLimit());
        //2 执行分页查询
        Long userId = BaseContext.getCurrentId();
        articleMapper.selectPage(page, new LambdaQueryWrapper<Article>()
                .eq(Article::getUserId, userId)
                .last("order by create_date desc"));
        PageResult list = getPageResult(page);
        return Result.success(list);
    }

    @Override
    public Result userDataList(PageQueryDTO dto) {

        Long userId = BaseContext.getCurrentId();

        List<UserData> userDataList = userDataMapper.selectList(new LambdaQueryWrapper<UserData>().
                eq(UserData::getUserId, userId)
                .eq(UserData::getType, dto.getType()));
        List<Long> ArticleIds = userDataList.stream()
                .map(userData -> userData.getArticleId())
                .collect(Collectors.toList());

        IPage<Article> page = new Page<>(dto.getPage(), dto.getLimit());
        articleMapper.selectPage(page, new LambdaQueryWrapper<Article>().in(Article::getId, ArticleIds));
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", getPageResult(page));
        return Result.success(map);
    }

    @Override
    public void editArticle(ArticleDTO dto) {
        Article article = BeanUtil.copyProperties(dto, Article.class);
        article.setUpdateDate(System.currentTimeMillis());
        articleMapper.updateById(article);
    }

    @Override
    public void update(UserDTO dto) {
        User user = BeanUtil.copyProperties(dto, User.class);
        uUserMapper.updateById(user);
    }

    @Override
    public void userDataHandle(UserHandleDTO dto) {
        Long userId = BaseContext.getCurrentId();
        //操作类型add
        if ("add".equals(dto.getAction())) {
            userDataMapper.insert(new UserData(
                    null,
                    dto.getArticle_id(),
                    userId,
                    dto.getType()
            ));
        }
        //操作类型del
        if ("del".equals(dto.getAction())) {
            userDataMapper.delete(new LambdaQueryWrapper<UserData>()
                    .eq(UserData::getUserId, userId)
                    .eq(UserData::getArticleId, dto.getArticle_id())
                    .eq(UserData::getType, dto.getType()));
        }
    }

    @Override
    public void addArticle(UserArticleDTO dto) {
        Article article = BeanUtil.copyProperties(dto, Article.class);
        article.setUserId(BaseContext.getCurrentId());
        article.setCreateDate(System.currentTimeMillis());
        article.setDefaultData("1");
        articleMapper.insert(article);
    }

    @Override
    public void delArticle(Long id) {
        articleMapper.deleteById(id);
    }

    private PageResult getPageResult(IPage page) {
        PageResult list = PageResult.builder()
                .count(page.getTotal())
                .totalPages(page.getPages())
                .pageSize(page.getSize())
                .currentPage(page.getCurrent())
                .data(page.getRecords())
                .build();
        return list;
    }

    //会员管理-------------------
    @Override
    public Result rowInfo(Long id) {
        User user = uUserMapper.selectById(id);
        return Result.success(user);
    }

    @Override
    public Result list(UserQueryPageDTO dto) {
        IPage<User> page = new Page(dto.getPage(), dto.getLimit());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(User::getUsername, dto.getUsername())
                .like(User::getMobile,dto.getMobile())
                .eq(User::getSex,dto.getSex());
        uUserMapper.selectPage(page, queryWrapper);
        
        return Result.success(getPageResult(page));
    }

    @Override
    public void add(UserDTO dto) {
        User user = BeanUtil.copyProperties(dto, User.class);
        uUserMapper.insert(user);
    }

    @Override
    public void del(Long id) {
        uUserMapper.deleteById(id);
    }
}
